package com.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * description IP地址工具 系统启动自动加载
 *
 * @title
 * @author tianzhou
 * @date 2023/7/24 20:21
 */


@Slf4j
@Component
public class IpConfig implements CommandLineRunner {

    @Value("${ip2regionXdbPath}")
    private String xdbPath;

    public static  byte[] vIndex;

    public void run(String... args ) throws Exception{

        // 1、从 dbPath 中预先加载 VectorIndex 缓存，并且把这个得到的数据作为全局变量，后续反复使用。
        try {
            log.info("开始加载xdb文件");
            vIndex = Searcher.loadVectorIndexFromFile(xdbPath);
            log.info("加载xdb文件成功");
        } catch (Exception e) {
            log.info("加载xdb信息{}异常：{}", xdbPath, e);
        }
    }
    public String getIpSource(String ipAdress) {

        // 使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithVectorIndex(xdbPath, vIndex);
        } catch (Exception e) {
            log.info("创建vectorIndex cached searcher失败{},{}", xdbPath, e);
            return null;
        }

        // 查询
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ipAdress);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            log.info("region: {}, ioCount: {}, took: {}", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            log.info("failed to search{}: {}", ipAdress, e);
            return null;
        }

        // 关闭资源
        try {
            searcher.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}